﻿using System;
using System.Collections.Generic;
using Microsoft.SharePoint;

namespace SecurityParser
{
    public class Web : SecurableObject
    {
        public List<RoleDefinition> Roles
        {
            get;
            set;
        }

        public override void Parse(SPWeb web)
        {
            //if this item should be deployed in the current configuration
            if (this.ShouldDeploy())
            {
                //Loop through the list of roles if there are any
                if (Roles != null)
                {
                    foreach (RoleDefinition role in Roles)
                    {
                        role.Attach(web);
                    }
                }

                //Call the base implementation of parse to parse the SecurableObject stuff

                //Since Web is a securable object with a url thats set in our elements file 
                //the reference to the SPWeb object passed into this method may be incorrect
                //verify it using the Url property

                if (string.Compare(web.Url, this.Url, true) != 0)
                {
                    //We need to get a reference to a different web
                    //Since SPWeb object implements IDisposable, wrap the call in a using statement
                    //to ensure that resources get disposed when we're done
                    string relativeUrl;

                    Uri newurl = new Uri(this.Url);
                    Uri current = new Uri(web.Url);

                    relativeUrl = newurl.MakeRelativeUri(current).ToString();

                    using (SPWeb newWeb = web.Site.OpenWeb(relativeUrl, true))
                    {
                        base.Parse(newWeb);
                    }
                }
                else
                {
                    base.Parse(web);
                }
            }
        }

    }
}
